<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>室内定位</title>
		<link rel="stylesheet" href="lib/bootstrap.min.css">
		<link rel="stylesheet" href="css/style.css">
		<script src="http://lib.baomitu.com/socket.io/2.0.1/socket.io.js"></script>
		<script src="js/math.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/mqtt.js" type="text/javascript" charset="utf-8"></script>

	</head>

	<body>
		<div id="fengMap"></div>
		<!--<div class="send" style="position: absolute;width: 80px;height: 80px;border: 1px sold;">
			发送
		</div>-->
		<!-- 视角按钮组 -->
		<div class="viewmode-group btn-group-vertical" data-toggle="buttons">
			<button class="btn btn-default">2D</button>
			<button class="btn btn-default btn-primary">3D</button>
		</div>

		<script src="lib/jquery-2.1.4.min.js"></script>
		<script src="lib/fengmap.min.js"></script>
		<script>
			//获取版本号,设置title
			document.title = '室内定位' + fengmap.VERSION;

			//定义全局map变量
			var map;
			var fmapID = 'location-test';
			var locationMarker;
			//楼层ID
			var lastGid = null;
			//第一人称、第三人称控制开关；定位跟随开关
			var others = true;
			var getData = {
				x: 14,
				y: 2
			}
			var layer = null
			var resultData = CoordTransform(getData)

			//起点终点坐标
			var points = [{
					'x': 13028213.4785,
					'y': 4737008.7298,
					groupID: 1
				},
				{
					x: 12961699.79823795,
					y: 4861826.46384646,
					groupID: 6
				}
			];
			window.onload = function() {
				map = new fengmap.FMMap({
					//渲染dom
					container: document.getElementById('fengMap'),
					//地图数据位置
					mapServerURL: './data/' + fmapID,
					//主题数据位置
					mapThemeURL: 'data/theme/',
					//设置主题
					defaultThemeName: '2001',
					// 默认比例尺级别设置为20级
					defaultMapScaleLevel: 22,
					//开启2维，3维切换的动画显示
					viewModeAnimateMode: true,
					//方向枚举型。可设置正南、正北、正东、正西、东南、西南等方向值。具体可参考fengmap.ControlsPoseEnum类。NORTH WEST SOUTH
					defaultControlsPose: fengmap.FMDirection.NORTH,
					defaultViewMode: fengmap.FMViewMode.MODE_2D, //初始二维还是三维状态，三维状态为MODE_3D,

					//开发者申请应用下web服务的key
					key: '670072019dff394f3f991e88e98024d5',
					//开发者申请应用名称
					appName: 'innerMap',
				});

				//打开Fengmap服务器的地图数据和主题
				map.openMapById(fmapID);

				//显示指北针
				map.showCompass = true;
				//地图加载完成回调
				map.on('loadComplete', function() {
					MqttWebSocketTest();

					addlocationMarker(points[0])
				});

				var aBtn = document.querySelectorAll('.btn');
				//开启2维模式
				aBtn[0].onclick = function() {
					//设置地图为2维模式
					map.viewMode = fengmap.FMViewMode.MODE_2D;
					this.classList.add('btn-primary');
					aBtn[1].classList.remove('btn-primary');
				};

				//开启3维模式
				aBtn[1].onclick = function() {
					//设置地图为3维模式
					map.viewMode = fengmap.FMViewMode.MODE_3D;
					this.classList.add('btn-primary');
					aBtn[0].classList.remove('btn-primary');
				};

				//添加定位点图层
				function addlocationMarker(coord) {
					locationMarker = new fengmap.FMLocationMarker({
						//设置图片的路径
						url: 'image/pointer.png',
						//设置图片显示尺寸
						size: 46,
						//设置图片高度
						height: 1,
					});
					//添加定位点标注
					map.addLocationMarker(locationMarker);
					//设置定位图标位置
					setLocationMakerPosition(coord);
					return locationMarker;
				};

				//设置图片标注点位置信息
				function setLocationMakerPosition(coord, angle, direction) {
					var data = {
						//设置定位点的x坐标
						x: coord.x,
						//设置定位点的y坐标
						y: coord.y,
						//设置定位点所在楼层
						groupID: coord.groupID,
						time: .50,
						callback: function() {
							//回调函数
						},
						zOffset: 1
					};
					//设置定位图标旋转角度
					if(direction) {
						locationMarker.rotateTo(-direction);
						if(others) {
							map.rotateTo({
								to: direction,
								time: 1
							});
						}
					}
					//不同楼层
					if(lastGid !== coord.groupID) {
						lastGid = coord.groupID;
						locationMarker.setPosition(data);
					}
					locationMarker.moveTo(data);
					map.moveTo({
						x: coord.x,
						y: coord.y,
						groupID: coord.groupID,
						time: 1
					});
				}

				function MqttWebSocketTest() {
//					var hostname = '172.16.10.13',
//					var hostname = 'dowin.natapp4.cc',
					var hostname = 'mqtt.dowino2o.net',
//					var hostname = '39.106.250.179',
						port = 8084,
//						port = 443,
						clientId = 'client-mao4999',
						timeout = 5,
						keepAlive = 100,
						cleanSession = false,
						ssl = true,
						userName = 'locationuser',
						password = 'dowin@#123',
//						topic = 'location',
						topic = 'test1',
						client = new Paho.MQTT.Client(hostname, port, clientId);
					//建立客户端实例  
					var options = {
						invocationContext: {
							host: hostname,
							port: port,
							path: '',
							clientId: clientId
						},
						timeout: timeout,
						keepAliveInterval: keepAlive,
						cleanSession: cleanSession,
						useSSL: ssl,
						userName: userName,
						password: password,
						onSuccess: onConnect,
						onFailure: function(e) {
							console.log(e);
							s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onFailure()}";
							console.log(s);
						}
					};
					client.connect(options);
					//连接服务器并注册连接成功处理事件  
					function onConnect() {
						console.log("onConnected");
						s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnected()}";
						console.log(s);
						client.subscribe(topic);
					}

					client.onConnectionLost = onConnectionLost;

					//注册连接断开处理事件  
					client.onMessageArrived = onMessageArrived;

					//注册消息接收处理事件  
					function onConnectionLost(responseObject) {
						console.log(responseObject);
						s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", onConnectionLost()}";
						console.log(s);
						if(responseObject.errorCode !== 0) {
							console.log("onConnectionLost:" + responseObject.errorMessage);
							console.log("连接已断开");
						}
					}
					//获取当前时间戳
					function getCurrentTime() {
						var timestamp = new Date().getTime();
						return timestamp;
					}

					function onMessageArrived(message) {
						console.log('收到时间：', getCurrentTime())
						console.log("收到消息:" + message.payloadString);
						var getStr = message.payloadString;
						var getObj = JSON.parse(getStr);
						console.log("收到消息对象:", getObj);
						if(isNaN(getObj.x)) {
							return false;
						}
						var newCoord = {
							'x': getObj.x,
							'y': getObj.y
						}
						var direction = getObj.sita;
						//转换后的地图坐标
						var mapCoord = CoordTransform(newCoord);
						setLocationMakerPosition(mapCoord, null, direction);
					}

					function send() {
						var s = {
							x: 12,
							y: 12,
							direction: 200
						};
						if(s) {
							//				s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (s) + ", from: web console}";
							s = "{openId:" + 'slsllssllslsl' + ", location:" + s + "}";
							message = new Paho.MQTT.Message(s);
							message.destinationName = topic;
							client.send(message);
							document.getElementById("msg").value = "";
						}
					}

					var count = 0;

					function start() {
						window.tester = window.setInterval(function() {
							if(client.isConnected) {
								var s = "{time:" + new Date().Format("yyyy-MM-dd hh:mm:ss") + ", content:" + (count++) +
									", from: web console}";
								message = new Paho.MQTT.Message(s);
								message.destinationName = topic;
								client.send(message);
							}
						}, 1000);
					}

					function stop() {
						window.clearInterval(window.tester);
					}

					Date.prototype.Format = function(fmt) { //author: meizz 
						var o = {
							"M+": this.getMonth() + 1, //月份 
							"d+": this.getDate(), //日 
							"h+": this.getHours(), //小时 
							"m+": this.getMinutes(), //分 
							"s+": this.getSeconds(), //秒 
							"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
							"S": this.getMilliseconds() //毫秒 
						};
						if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
						for(var k in o)
							if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
								k]) : (("00" + o[k]).substr(("" + o[k]).length)));
						return fmt;
					}

				}
			};

			function CoordTransform(Coord) {
				//创建转换器
				var trasformer = new fengmap.MapCoordTransform();
				//来至定位系统的参数 定位的原点坐标 已经定位的范围,(矩形对角线的2个点)
				var locOrigion = {
					'x': 0,
					'y': 0
				}; //定位坐标原点
				var locRange = {
					'x': 32.387,
					'y': 32.202
				}; //定位范围

				//根据定位四个角点的地图坐标点
				var mapParas = [];

				mapParas[0] = {
					'x': 13028246.5092,
					'y': 4737041.7885
				}; //定位原点地图坐标
				mapParas[1] = {
					'x': 13028214.3369,
					'y': 4737041.7511
				}; //X轴终点地图坐标
				mapParas[2] = {
					'x': 13028214.2996,
					'y': 4737009.4296
				}; //定位原点对角点地图坐标
				mapParas[3] = {
					'x': 13028246.4345,
					'y': 4737009.5043
				}; //Y轴终点地

				//转换器初始化
				trasformer.init(locOrigion, locRange, mapParas);

				//定位系统中的定位坐标
				var loc = {
					'x': Coord.x,
					'y': Coord.y
				}; //定位系统所返回的坐标点

				//转换后的地图坐标
				var mapCoord = trasformer.transform(loc);
				return mapCoord;
			}
		</script>
	</body>

</html>